﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace QLNS.Models
{
    public class NguoiDungModels
    {
        public static byte[] encryptData(string data)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hashedBytes;
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(data));
            return hashedBytes;
        }

        public static string md5(string data)
        {
            return BitConverter.ToString(encryptData(data)).Replace("-", "").ToLower();
        }

        public static NguoiDung DangNhap(NguoiDung tk)
        {
            string mk = md5(tk.MatKhau);
            ITAPMNS2013Entities context = new ITAPMNS2013Entities();
            var query = from s in context.DSNguoiDung
                        where s.TaiKhoan == tk.TaiKhoan && s.MatKhau == mk
                        select s;
            return query.FirstOrDefault();
        }       

        public static NguoiDung GetChiTietNguoiDung(int id)
        {
            //khoi tao db
            ITAPMNS2013Entities context = new ITAPMNS2013Entities();
            var query = (from s in context.DSNguoiDung
                         where s.ID == id
                         select s).FirstOrDefault();
            return query;

        }
        public static void Add(NguoiDung th)
        {
            th.MatKhau = md5(th.MatKhau);
            ITAPMNS2013Entities context = new ITAPMNS2013Entities();
            context.DSNguoiDung.AddObject(th);
            context.SaveChanges();
        }
        
        public static void Delete(int id)
        {
            ITAPMNS2013Entities context = new ITAPMNS2013Entities();
            var query = (from h in context.DSNguoiDung
                         where h.ID == id
                         select h).FirstOrDefault();

            context.DSNguoiDung.DeleteObject(query);
            context.SaveChanges();

        }

        
        public static void Update(NguoiDung id)
        {
            ITAPMNS2013Entities context = new ITAPMNS2013Entities();
            var query = from h in context.DSNguoiDung
                        where h.ID == id.ID
                        select h;
            NguoiDung kq = query.First<NguoiDung>();
            if (id.MatKhau != "")
                id.MatKhau = md5(id.MatKhau);
            else id.MatKhau = kq.MatKhau;
            kq = id;                            
            context.DSNguoiDung.ApplyCurrentValues(kq);
            context.SaveChanges();

        }
    }
}